package com.uit.httt04.duongvanlam.facedetection.xml;

import static com.googlecode.javacv.cpp.opencv_core.*;

public class MatrixXML extends Object
{
	private int height;
	private int width;
	private String data;

	public int getHeight()
	{
		return height;
	}

	public void setHeight(int height)
	{
		this.height = height;
	}

	public int getWidth()
	{
		return width;
	}

	public void setWidth(int width)
	{
		this.width = width;
	}

	public String getData()
	{
		return data;
	}

	public void setData(String data)
	{
		this.data = data;
	}

	public MatrixXML Copy()
	{
		MatrixXML matrixXML = new MatrixXML();
		//
		matrixXML.setData(this.getData());
		matrixXML.setHeight(this.getHeight());
		matrixXML.setWidth(this.getWidth());
		//
		return matrixXML;
	}

	public static String MatrixToString(char SplitBy, CvMat matrix)
	{
		if (matrix != null && matrix.empty() == false && matrix.rows() > 0 && matrix.cols() > 0 && matrix.channels() == 1)
		{

			int totalAmountOfElements = matrix.rows() * matrix.cols();

			double firstValue = cvGetReal2D(matrix, 0, 0);

			int capacity = (String.valueOf(firstValue).length() + 1) * totalAmountOfElements;

			StringBuilder result = new StringBuilder(capacity);

			for (int i = 0; i < matrix.rows(); i++)
			{
				for (int j = 0; j < matrix.cols(); j++)
				{
					result.append(String.valueOf(cvGetReal2D(matrix, i, j)));
					result.append(SplitBy);
				}
			}

			return result.toString();
		}

		return null;
	}

	public static CvMat MatrixXMLToCvMat(char SplitBy, String Data, int Height, int Width)
	{
		try
		{
			CvMat result = cvCreateMat(Height, Width, CV_32FC1);

			String[] splittedData = Data.split(String.valueOf(SplitBy));

			if (splittedData.length == (Height * Width)) // 1_2_3_4_5_6_7_8_9_10_11_12_13_
			{
				for (int i = 0; i < Height; i++)
				{
					for (int j = 0; j < Width; j++)
					{
						cvSetReal2D(result, i, j, Double.valueOf(splittedData[i * Width + j]));
					}
				}

				return result;
			}

			return null;
		}
		catch (Exception e)
		{
			return null;
		}
	}

	@Override
	public void finalize() throws Throwable
	{
		super.finalize();
	}
	//
}
